# -*- coding: utf-8 -*-
import json
import time
from hashlib import md5

import redis
import requests

import setting


class WechatToken(object):

    def __init__(self):
        self.redis = redis.StrictRedis(host=setting.redis_host, port=setting.redis_port)

        self.SOURCE_FROM = "JSJ"
        self.GET_ACCESS_TOKEN = "http://s5.jsjinfo.cn/awkmanage/v3/ktapi/GetAccessToken"
        self.MD5_KEY_JINSESHIJI = "#wugf543sxcv5*$#"

        self.init()

    @property
    def access_token(self):
        if setting.product_env == 0:
            d = self.redis.get("kt:wechat_public_token_1")
            data = json.loads(d) if d else {}
            return data.get("access_token", "") if data else ""
        else:
            return self._get_kt_access_token()

    def _get_kt_access_token(self):
        TimeStamp = str(int(time.time()))
        param = {
            "RequestHead": {
                "TimeStamp": TimeStamp,
                "SourceFrom": self.SOURCE_FROM,
                "Sign": self._gen_sign(TimeStamp)
            },
            "RequestBody": {}
        }
        print param
        headers = {'content-type': 'application/json'}
        res = requests.post(self.GET_ACCESS_TOKEN, json.dumps(param), headers=headers, timeout=3).json()
        if res.get("ResponseBody", 0):
            return res.get("ResponseBody").get("AccessToken")

        return None

    def _gen_sign(self, TimeStamp):
        return md5("TimeStamp=" + TimeStamp + "&SourceFrom=" + self.SOURCE_FROM + "&" + self.MD5_KEY_JINSESHIJI).hexdigest()

